package com.chain.BrotherExchange.ui.adapter;

import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.chain.BrotherExchange.R;
import com.chain.BrotherExchange.data.model.BannerList;
import com.chain.BrotherExchange.ui.activity.WebViewActivity;
import com.chain.BrotherExchange.utils.ImageViews;

import java.util.List;

/**
 * 首页图片广告
 */
public class ImageAdvertsAdapter extends RecyclerView.Adapter<ImageAdvertsAdapter.ViewHolder> {

    private List<BannerList.DataBean.ListBean> mBannerList;

    public ImageAdvertsAdapter(List<BannerList.DataBean.ListBean> bannerList) {
        this.mBannerList = bannerList;
    }

    public void setAdverts(List<BannerList.DataBean.ListBean> bannerList) {
        this.mBannerList = bannerList;
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int position) {
        return new ViewHolder(LayoutInflater.from(viewGroup.getContext())
                .inflate(R.layout.item_home_adverts, viewGroup, false));
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        BannerList.DataBean.ListBean banner = mBannerList.get(position % mBannerList.size());
        ImageViews.load(banner.getPicturePath(), holder.mAdvertImageView);

        String bannerLinkPath = banner.getLinkPath();
        if (!TextUtils.isEmpty(bannerLinkPath) && !TextUtils.isEmpty(bannerLinkPath.trim())){
            holder.itemView.setOnClickListener(v ->
                    WebViewActivity.launch(v.getContext(), banner.getLinkPath()));
        }
    }

    @Override
    public int getItemCount() {
        return Integer.MAX_VALUE;
    }

    class ViewHolder extends RecyclerView.ViewHolder {

        private final ImageView mAdvertImageView;

        ViewHolder(@NonNull View itemView) {
            super(itemView);
            mAdvertImageView = itemView.findViewById(R.id.advert_image);
        }
    }
}
